//
//  GHShopCardViewController.m
//  GodHorses
//
//  Created by Mac on 2017/11/20.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "GHShopCardViewController.h"
#import "GHShopCardModel.h"
#import "GHShopCardTableViewCell.h"
#import "GHMineOrderViewController.h"
@interface GHShopCardViewController ()
@property(nonatomic, strong) NSMutableArray <GHShopCardModel*>    *dataSouce;//数据源
@property(nonatomic, strong) UIView                                *bootomView;
@property(nonatomic, strong) STButton                              *allChosedButton;
@property(nonatomic, strong) STLabel                               *totalLable;
@property(nonatomic, strong) GHNoResultView                        *noResultView;
@end

@implementation GHShopCardViewController
- (void)dealloc{
    NSLog(@"GHShopCardViewController dealoc");
}
#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"购物车";
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self sendMyshopCardRequest];
    }];
    
    [self configSubView];
    [self st_setRightItemWithTitle:@"删除" titleColor:[UIColor whiteColor]];
    //无数据view
    self.noResultView = [[GHNoResultView alloc] initWithFrame:CGRectMake(0, 100, UIScreenWidth, 350) title:@"购物车空空如也" buttonTitle:@"快去购买商品吧" buttonHandle:^(NSString *titleString) {
        
    }];
    self.noResultView.hidden = YES;
    [self.tableView addSubview:self.noResultView];
    
}
#pragma mark --subView
- (void)configSubView{
    self.tableView.st_height = self.tableView.st_height - 50;
    self.bootomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 50)];
    self.bootomView.backgroundColor = [UIColor whiteColor];
    [self.bootomView st_showTopShadow];
    self.bootomView.bottom = UIScreenHeight -64;
    [self.view addSubview:self.bootomView];
    __weak typeof(self) weakSelf =  self;
    self.allChosedButton = [[STButton alloc] initWithFrame:CGRectMake(10, 0, 60, 50)
                                                     title:@"全选"
                                                titleColor:GH_YellowBackGroundColor
                                                 titleFont:15
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"PC_gouxuan_background"]];
    [self.allChosedButton setImage:[UIImage imageNamed:@"PC_gouxuan__selected_red"] forState:UIControlStateSelected];
    [self.allChosedButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedAllButtonWithSender:sender];
    }];
    [self.allChosedButton makeImageRight];
    [self.bootomView addSubview:self.allChosedButton];
    
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 100, 50)
                                                     title:@"结算"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:15
                                              cornerRadius:0
                                           backgroundColor:FlatOrange
                                           backgroundImage:nil
                                                     image:nil];
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    buyButton.st_right = UIScreenWidth;
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedBuyButton];
    }];
    [self.bootomView addSubview:buyButton];
    self.totalLable = [[STLabel alloc] initWithFrame:CGRectMake(_allChosedButton.st_right + 5, 0, buyButton.st_left - 10 - _allChosedButton.st_right, 50)
                                                text:@"合计:￥0"
                                                textColor:GH_redColor
                                                     font:13
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    [self.totalLable.text st_convertAttributeStringWithKeyWord:[NSString stringWithFormat:@"%@",@"合计:"]
                                                    attributes:@{NSForegroundColorAttributeName:GH_YellowBackGroundColor,
                                                                 NSFontAttributeName:[UIFont systemFontOfSize:15]
                                                                 }];
    [self.bootomView addSubview:self.totalLable];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count ;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [GHShopCardTableViewCell cellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 44;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 44)];
    headerView.backgroundColor = [UIColor whiteColor];
    STButton * iconButton = [[STButton alloc] initWithFrame:CGRectMake(10, 0, UIScreenWidth - 20, 44)
                                                      title:@"神马国际"
                                                 titleColor:GH_firstTextColor
                                                  titleFont:16
                                               cornerRadius:0
                                            backgroundColor:nil
                                            backgroundImage:nil
                                                      image:[UIImage imageNamed:@"logo"]];
    iconButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [headerView addSubview:iconButton];
    return headerView;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    GHShopCardTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[GHShopCardTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    __weak typeof(self) weakSelf =  self;
    [cell.chosedButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedChosedButtonIndexPath:indexPath];
    }];
    cell.model = self.dataSouce[indexPath.row];
    
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Action Method
//单词更改状态
- (void)onSelectedChosedButtonIndexPath:(NSIndexPath*)indexpath{
    GHShopCardModel * model = self.dataSouce[indexpath.row];

    [self sendOneGoodSeletedRequest:model.shopCardId successHandle:^(NSString *total_price, NSString *selected) {
        model.selected = selected;
        [self caclutAllPrice];
        [self.tableView reloadData];

    }];

}
//点击结算
- (void)onSlectedBuyButton{
    [self sendMakeOrderRequest];
}
//点击全选
- (void)onSlectedAllButtonWithSender:(UIButton*)sender{
    sender.selected = !sender.selected;
    [self sendAllGoodSeletedRequest:[NSNumber numberWithBool:sender].integerValue successHandle:^(NSString *total_price, NSString *selected) {
        [self setAlltitleWithAllPrice:total_price.floatValue];
        for (GHShopCardModel * model in self.dataSouce) {
            model.selected = selected;
        }
        [self.tableView reloadData];
    }];
    //计算钱
}
- (void)st_rightBarAction:(id)sender{
    [self showAlertCancelAndConfirm:@"确定要删除勾选的商品吗?" andWithBlock:^(NSString *name) {
        if ([name isEqualToString:@"确认"]) {
            [self sendDelShopCardRequest];
        }
    }];
}
#pragma mark --Private Method
//计算所有钱
- (void)caclutAllPrice{
    CGFloat allPrice = 0;
    for (GHShopCardModel * model in self.dataSouce){
        if (model.selected.boolValue) {
            allPrice = allPrice + [model.total_price floatValue];
        }
    }
    [self setAlltitleWithAllPrice:allPrice];
}
- (void)setAlltitleWithAllPrice:(CGFloat)allPrice{
    self.totalLable.text = [NSString stringWithFormat:@"合计:￥%0.2f",allPrice];
    self.totalLable.attributedText =
    [self.totalLable.text st_convertAttributeStringWithKeyWord:[NSString stringWithFormat:@"%@",@"合计:"]
                                                    attributes:@{NSForegroundColorAttributeName:GH_YellowBackGroundColor,
                                                                 NSFontAttributeName:[UIFont systemFontOfSize:15]
                                                                 }];
}


#pragma mark --NetWork Method
- (void)sendMyshopCardRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/goods/get_shopping_cart"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 NSArray * array =  responseObject[@"data"];
                                                 self.dataSouce = [NSMutableArray new];
                                                 BOOL allSelected = YES;//全选默认yes
                                                 for (NSDictionary * shopDic in array) {
                                                     GHShopCardModel * model = [GHShopCardModel mj_objectWithKeyValues:shopDic];
                                                     [self.dataSouce addObject:model];
                                                     if (!model.selected.boolValue) {
                                                         allSelected = NO;
                                                     }
                                                 }
                                                 self.allChosedButton.selected = allSelected;
                                                 [self caclutAllPrice];
                                                 [self.tableView reloadData];
                                                 self.noResultView.hidden = self.dataSouce.count;
                                                 [self.tableView.mj_header endRefreshing];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 self.dataSouce = [NSMutableArray new];
                                                 self.noResultView.hidden = self.dataSouce.count;
                                                 [self.tableView reloadData];
                                                 [SVProgressHUD dismiss];
                                                 //[SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
//下订单
- (void)sendMakeOrderRequest{
    
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    NSString * attSrting = [[self.totalLable.text componentsSeparatedByString:@"￥"] lastObject];
    CGFloat money = [attSrting floatValue];
    if (money < 1) {
        [SVProgressHUD showErrorWithStatus:@"您还没有勾选任何商品"];
        return;
    }
    [dic setValue:@(money) forKey:@"total_fee"];
    [SVProgressHUD showWithStatus:@"请稍后"];
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/goods/add_order"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"添加订单成功"];
                                                 GHMineOrderViewController * vc = [GHMineOrderViewController new];
                                                 vc.currentTitle = @"待付款";
                                                 [self.navigationController pushViewController:vc animated:YES];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
//更改商品选中状态
- (void)sendOneGoodSeletedRequest:(NSString*)shopId  successHandle:(void(^)(NSString * total_price,NSString * selected))successHandle{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    
    [dic setObject:shopId forKey:@"cart_id"];
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/goods/change_check"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * dataDic = responseObject[@"data"];
                                                 NSString * total_price;
                                                 if ([dataDic.allKeys containsObject:@"total_price"]) {
                                                     total_price = dataDic[@"total_price"];
                                                 }
                                                 NSString * selected;
                                                 if ([dataDic.allKeys containsObject:@"selected"]) {
                                                     selected = dataDic[@"selected"];
                                                 }
                                                 if (successHandle) {
                                                     successHandle(total_price,selected);
                                                 }
                                                
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendAllGoodSeletedRequest:(NSInteger)selsected  successHandle:(void(^)(NSString * total_price,NSString * selected))successHandle{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    
    [dic setObject:@(selsected) forKey:@"selected"];
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/goods/all_check"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * dataDic = responseObject[@"data"];
                                                 NSString * total_price;
                                                 if ([dataDic.allKeys containsObject:@"total_price"]) {
                                                     total_price = dataDic[@"total_price"];
                                                 }
                                                 NSString * status;
                                                 if ([dataDic.allKeys containsObject:@"status"]) {
                                                     status = dataDic[@"status"];
                                                 }
                                                 if (successHandle) {
                                                     successHandle(total_price,status);
                                                 }
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendDelShopCardRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:@"http://www.smqyp.com/Api/goods/delete_cart"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                                                 [self.tableView.mj_header beginRefreshing];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end
